<script setup lang="ts">
import ActivityAPI from "@/api/activity";
import { ref, reactive, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';


/**
 * @author lwlianghehe@gmail.com
 * @date 2025/05/29 14:24
 */
const title = ref<string>("");
const handleQuery = () => {
  loadData(1);
  title.value = "";
};

// 初始表单数据
const initialFormData = {
  title: "",
  description: "",
  startTime: "",
  endTime: "",
  point: 0,
  poster: "",
  ruleDescription: "",
  maxParticipants: 0 // 默认值为0，表示无上限
};

// 修改
const handleOpenDialog = async (id?: number) => {
  if (id) {
    formData.value = await ActivityAPI.get(id);
    // 初始化海报文件列表
    if (formData.value.poster) {
      posterFileList.value = [{
        name: '海报',
        url: formData.value.poster
      }];
    }
    dialog.value.visible = true;
  } else {
    formData.value = { ...initialFormData };
    posterFileList.value = [];
    dialog.value.visible = true;
  }
};
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    ActivityAPI.delete(id).then(() => {
      ElMessage.success("删除成功");
      loadData(pageNum.value); // 刷新当前页数据
    });
  });
};

const loading = ref(false);
const pageData = ref<any[]>([]); // 明确类型为数组

const handleSelectionChange = () => {};

const total = ref<number>(0);
const pageNum = ref(1);
const pageSize = ref(10); // 每页显示数量

// 分页加载数据
const loadDataPage = async (
  title: string,
  pageNum: number,
  pageSize: number
) => {
  return await ActivityAPI.getPage(title, pageSize, pageNum);
};

const loadData = async (num: number) => {
  loading.value = true; // 显示加载状态
  pageNum.value = num;
  try {
    const data = await loadDataPage(title.value, num, pageSize.value);
    total.value = data.total;
    pageData.value = data.records;
  } catch (error) {
    console.error('加载数据失败', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false; // 隐藏加载状态
  }
};

// 初始加载数据
loadData(1);

// 新增 修改
const activityFormRef = ref(); // 表单
const handleSubmit = () => {
  if (activityFormRef.value) {
    activityFormRef.value.validate((valid: boolean) => {
      if (valid) {
        // 验证成功
        ActivityAPI.save(formData.value).then((data) => {
          if (formData.value.id) {
            // 修改
            ElMessage.success("修改活动成功");
          } else {
            // 新增
            ElMessage.success("新增活动成功");
          }
          handleCloseDialog();
          loadData(pageNum.value); // 刷新当前页数据
        });
      }
    });
  }
};
const handleCloseDialog = () => {
  dialog.value.visible = false;
};

const formData = ref<any>({
  ...initialFormData
});
const drawerSize = ref<number>(500);
const dialog = ref({
  visible: false,
  title: "活动"
});

const rules = reactive({
  title: [{ required: true, message: "活动标题不能为空", trigger: "blur" }],
  startTime: [{ required: true, message: "开始时间不能为空", trigger: "change" }],
  endTime: [{ required: true, message: "结束时间不能为空", trigger: "change" }],
  poster: [{ required: true, message: '请上传活动海报', trigger: 'blur' }]
})

// 海报上传相关
const posterFileList = ref<any[]>([]);

// 上传前的验证
const beforePosterUpload = (file: File) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }

  return isImage && isLt2M;
};

// 上传成功处理
const handlePosterSuccess = (response: any) => {
  console.log('Upload response:', response); // 打印看看实际结构

  let url = '';

  if (typeof response === 'string') {
    url = response;
  } else if (response.url) {
    url = response.url; // 从response中获取url
  } else if (response.data?.url) {
    url = response.data.url;
  }

  if (url) {
    formData.value.poster = url;
    ElMessage.success('海报上传成功');
  } else {
    ElMessage.error('海报上传失败，请重试');
  }
};

// 删除海报处理
const handlePosterRemove = () => {
  formData.value.poster = '';
};

// 图片预览URL计算属性
const posterPreviewUrl = computed(() => {
  return formData.value.poster || '';
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="title"
            placeholder="活动标题"
            style="width: 240px"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-card shadow="hover" class="data-table">
        <div class="data-table__toolbar">
          <el-button type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="pageData"
          border
          stripe
          highlight-current-row
          class="data-table__content"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="活动标题" prop="title" />
          <el-table-column label="活动描述" prop="description" />
          <el-table-column label="开始时间" prop="startTime" />
          <el-table-column label="结束时间" prop="endTime" />
          <el-table-column label="积分" prop="point" />
          <el-table-column label="海报" prop="poster">
            <template #default="scope">
              <el-image
                v-if="scope.row.poster"
                :src="'api'+ scope.row.poster"
                :preview-src-list="[scope.row.poster]"
                style="width: 60px; height: 60px; border-radius: 4px;"
                fit="cover"
                preview-teleported
                hide-on-click-modal
              />
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="规则描述" prop="ruleDescription" />
          <!--          <el-table-column label="最大参与人数" prop="maxParticipants" width="150" />-->

          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleOpenDialog(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                icon="delete"
                link
                size="small"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="data-el-pagination">
          <el-pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="(size) => loadData(1)"
            @current-change="(page) => loadData(page)"
          />
        </div>
      </el-card>
    </div>

    <!-- 活动表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form
        ref="activityFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="formData.title"
            :readonly="!!formData.id"
            placeholder="请输入活动标题"
          />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="formData.description"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input
            v-model="formData.point"
            placeholder="请输入积分"
          />
        </el-form-item>
        <el-form-item label="海报" prop="poster">
          <el-upload
            action="/api/api/file/upload"
            :limit="1"
            :before-upload="beforePosterUpload"
            :on-success="handlePosterSuccess"
            :on-remove="handlePosterRemove"
            :file-list="posterFileList"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持 JPG/PNG 格式，大小不超过 2MB
              </div>
            </template>
          </el-upload>
          <div v-if="posterPreviewUrl" class="preview-container">
            <div class="preview-title">海报预览：</div>
            <el-image
              :src="'/api'+posterPreviewUrl"
              class="upload-preview"
              :preview-src-list="['/api'+posterPreviewUrl]"
              fit="contain"
              preview-teleported
              hide-on-click-modal
            />
          </div>
        </el-form-item>
        <el-form-item label="规则描述" prop="ruleDescription">
          <el-input
            v-model="formData.ruleDescription"
            placeholder="请输入规则描述"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <!--        <el-form-item label="最大参与人数" prop="maxParticipants">-->
        <!--          <el-input-number v-model="formData.maxParticipants" :min="0" placeholder="请输入最大参与人数（0表示无上限）" />-->
        <!--        </el-form-item>-->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style scoped lang="scss">
.upload-preview {
  margin-top: 10px;
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  display: block;
}

.preview-container {
  margin-top: 15px;
}

.preview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

:deep(.el-upload-list__item) {
  transition: none !important;
}
</style>
